﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Jage.Logic.Resources;

namespace Jage.GameEditor.Controls.Sprites
{
    public partial class SpritePreview : UserControl
    {
        public SpritePreview()
        {
            InitializeComponent();
        }

        public void SetResource(string resource)
        {
            PreviewSprite = ResourceIO.GetBitmap(resource);
        }

        public void SetResource(string resource, Point origin)
        {
            PreviewSprite = ResourceIO.GetBitmap(resource);
            Origin = origin;
            Refresh();
        }

        private void PanelPreviewSpritePaint(object sender, PaintEventArgs e)
        {
            if (PreviewSprite == null) return;
            var spriteWidth = PreviewSprite.Width;
            var width = Math.Min(Width, spriteWidth);
            var spriteHeight = PreviewSprite.Height;
            var zoom = (float) width/spriteWidth;
            e.Graphics.DrawImage(PreviewSprite, new Rectangle(0, 0, width, (int)(zoom * spriteHeight)));
            if (Origin.HasValue) DrawOriginMark(e.Graphics, new Point((int)(zoom * Origin.Value.X), (int)(zoom * Origin.Value.Y)));
        }

        private void DrawOriginMark(Graphics graphics, Point origin)
        {
            graphics.DrawLine(Pens.Cyan, origin.X, origin.Y - 2, origin.X, origin.Y + 2);
            graphics.DrawLine(Pens.Cyan, origin.X - 2, origin.Y, origin.X + 2, origin.Y);
        }

        private Bitmap _previewSprite;

        private Bitmap PreviewSprite
        {
            get
            {
                return _previewSprite;
            }
            set
            {
                _previewSprite = value;
                Visible = _previewSprite != null;
                Refresh();
            }
        }

        public Point? Origin { get; set; }

    }
}
